/*
 * Indiana University Community Grid Computing Lab Software License,Version 1.1
 *
 * Copyright (c) 2002 Community Grid Computing Lab, Indiana University.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *      "This product includes software developed by the Indiana University
 *       Community Grid Computing Lab (http://www.communitygrids.iu.edu/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Indiana Univeristy","Indiana Univeristy Pervasive Techonology
 *    Labs" and  "Indiana Univeristy Community Grid Computing Lab" must not be
 *    used to endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    http://www.communitygrids.iu.edu/.
 *
 * 5. Products derived from this software may not use "Indiana
 *    University" name nor may "Indiana University" appear in their name,
 *    without prior written permission of the Indiana University.
 *
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * INDIANA UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 *
 * <p>Title: SensorGrid</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author Galip Aydin
 * @version 1.0
 */

package cgl.sensorgrid.filters;

import cgl.narada.event.*;
import cgl.sensorgrid.filters.*;
import java.io.*;
import cgl.sensorgrid.xml.binary.adapters.*;
import java.nio.ByteBuffer;
import java.util.*;
import org.jvnet.fastinfoset.FastInfosetSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import com.sun.xml.fastinfoset.sax.SAXDocumentParser;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import javax.xml.transform.*;
import javax.xml.transform.*;

public class BinaryFilter extends Filter {
    public BinaryFilter() {
    }

    private FileWriter fw;
//    FileOutputStream fos;
//    FileOutputStream fos_xml;
    private String mode;
    private StringBuffer perfBuffer = new StringBuffer();

    private ByteArrayInputStream bis;
    private ByteArrayOutputStream out;
    private BNUX bnux = new BNUX();
    private Transformer tx;
    private FIConverter ficonverter;

    private SAXDocumentParser s = new SAXDocumentParser();
    private SAXSource ss;
    private StreamResult sr;
    private String perfPath;
    public static boolean nano;

    public BinaryFilter(String[] argsa, String _mode, String perfPath_) {
        bnux = new BNUX();
        nano = true;
        this.initialize(argsa);
        this.mode = _mode;
        try {
            tx = TransformerFactory.newInstance().newTransformer();
//            fw = new FileWriter(
//                    "C:/projects/XML/perf/filter-perf-bnux-05-24.txt");
            perfPath = perfPath_;
            fw = new FileWriter(this.perfPath);
            fw.write("# Filter Mode=" + mode + "\n#");
            fw.flush();
//            fos_xml = new FileOutputStream("C:/projects/XML/perf/binary/fi-1.txt");
        } catch (Exception ex) {
        }
    }


//    private Object syncObj1 = new Object();
//    private List eventList = Collections.synchronizedList(new LinkedList());
//
//    public void addEvent(NBEvent event) {
//        synchronized (syncObj1) {
//            eventList.add(event);
//            if (eventList.size() == 1) {
//                syncObj1.notify();
//            }
//        }
//    }


//    public void run() {
//        boolean running = true;
//        try {
//            while (running) {
//                synchronized (syncObj1) {
//                    if (eventList.size() == 0) {
//                        syncObj1.wait();
//                    }
//                    byte[] data2 = ((NBEvent) eventList.remove(0)).
//                                   getContentPayload();
//                    if (data2 != null && data2.length > 0) {
//                        tstartreceive = System.currentTimeMillis();
////                           tstartreceive = System.nanoTime();
//                        out = new ByteArrayOutputStream();
//
//                        //bis = new ByteArrayInputStream(data2);
////                        fi2xml_jaxp(new ByteArrayInputStream(data2), out);
////                        parse_fi_sax_xml(new ByteArrayInputStream(data2), out);
////                        tbinary = System.nanoTime();
//                        tbinary = System.currentTimeMillis();
//                        //System.out.println((tbinary-tstartreceive));
////                        fos.write(out.toByteArray());
////                        fos.flush();
//
////                        tendreceive = System.nanoTime();
//                        tendreceive = System.currentTimeMillis();
//                        perfBuffer.append("\n" + tstartreceive + "\t" + tbinary +
//                                          "\t" +
//                                          tendreceive);
//                        //bis.close();
//                        out.close();
////                        System.out.println(tbinary + "\t" + tstartreceive +
////                                           "\t" + tendreceive);
//
//                    }
//                }
//            }
//            return;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }

    public void setMode(String mode_) {
        System.out.println("setting mode " + mode_);
        this.mode = mode;
    }

    long tstartreceive;
    long tendreceive;
    long tbinary;
    Vector msgvec = new Vector();
    static boolean end = false;
    static boolean start = false;
    int cnt = 50;
    String path = "C:/projects/XML/fi/gml/" + cnt;



    public void testFIC() {
        try {
//            FIConverter fic = new FIConverter(new FileInputStream(
//                    "C:/projects/XML/data/global-seismic-1900-1971.finf"),
//                                              new ByteArrayOutputStream());
            FIConverter fic = new FIConverter();
            fic.run();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    int featurecount = 0;
    private static int eventCount=0;
    private int events=0;
    /**
      *
      * @param nbEvent NBEvent
      */
     public void onEvent(NBEvent nbEvent) {
         try {
             if (nbEvent.getEventProperties().hasProperties()) {
                 if (nbEvent.getEventProperties().getProperty("MARKER") != null) {
                     String marker = (String) nbEvent.getEventProperties().
                                     getProperty("MARKER");
                     if (marker.equals("EOF")) {
                         fw.write(perfBuffer.toString() + "\n#\n#\n#");
                         fw.flush();
                         perfBuffer = new StringBuffer();
                         cnt += 50;
//                              File f = new File("C:/projects/XML/fi/gml/"+ cnt);
//                              f.mkdir();
//
//                              path="C:/projects/XML/fi/gml/"+ cnt;
                         System.out.println("# of Features Per Line = " + cnt);
                         events=0;
//                              fos_xml.close();
//                              fos_xml = new FileOutputStream("C:/projects/XML/perf/binary/" + System.currentTimeMillis()+ ".xml");
                     }
//                           if(marker.equals("SOM")){
//                               System.out.println("SOM");
//                               msgvec = new Vector();
//                               start = true;
//                               end=false;
//                           }
//                           if(marker.equals("EOM")){
//                               System.out.println("EOM");
//                               start=false;
//                               end = true;
//                           }
                 }
             }

             String msg = "";
             if (nbEvent.getContentPayload() != null) {
                 byte[] message = null;
                 message = nbEvent.getContentPayload();
                 tstartreceive = getTime();

                 if (message.length > 0) {

                     if (mode.equalsIgnoreCase("BNUX")) {
                         bis = new ByteArrayInputStream(message);
                         out = new ByteArrayOutputStream();
                        tstartreceive = getTime();
                         out = bnux.bnux2xml(bis);
                        tbinary = getTime();
//                        out.toByteArray();
//                        msg = new String(out.toByteArray());

                        tendreceive = getTime();
                        perfBuffer.append("\n" + tstartreceive + "\t" + tbinary +
                                           "\t" +
                                           tendreceive);
                     }

                     else if (mode.equalsIgnoreCase("FI")) {
//                         System.out.println("eventCount = " + events++ + "/" + eventCount++ );

                         //addEvent(nbEvent);
                         ByteArrayInputStream in = new ByteArrayInputStream(
                                 nbEvent.getContentPayload());
                         ByteArrayOutputStream bos = new ByteArrayOutputStream();
                         tstartreceive = getTime();
                         tx.transform(new FastInfosetSource(in),
                                      new StreamResult(bos));

                         //byte[] by = bos.toByteArray();
                     //                         System.out.println(new String(by));
                     //                         fos_xml.write(by);
                     //                         fos_xml.flush();
                     //                         fos_xml.close();
                     //                         fos_xml = new FileOutputStream("C:/projects/XML/perf/binary/" + System.currentTimeMillis()+ ".xml");

                         tbinary = getTime();
                         in.close();
                         bos.close();
                         perfBuffer.append("\n" + tstartreceive + "\t" + tbinary);
                         System.gc();
                     }

                     else if (mode.equalsIgnoreCase("XML")) {
                         tstartreceive = System.nanoTime();

                         msg = new String(message);
                         OutputStream os = new ByteArrayOutputStream();
                         os.write(message);

//                         tendreceive = getTime();
                         tendreceive = System.nanoTime();
                         perfBuffer.append("\n" + tstartreceive + "\t" + tendreceive);
//                         System.out.print("\n" + tstartreceive + "\t" + tendreceive);
                         //System.gc();
                     } else {
                         msg = new String(message);
                         System.err.println(msg);
                     }
                 }
             }
         } catch (Exception ex) {
             ex.printStackTrace();
         }
    }

    public long getTime(){
        if(nano)
            return System.nanoTime();
        else
            return System.currentTimeMillis();
    }

    /**
     *
     * @param args String[]
     */
    public static void main(String[] args) {
        try {
            if (args.length < 6) {
                System.out.println("Usage: java cgl.sensorgrid.sopac.gps.filters.BinaryFilter commType nbHost nbPort subTopic perfPath mode");
                System.exit(0);
            }
            String commType = args[0];
            String nbHost = args[1];
            String nbPort = args[2];
            String subTopic = args[3];
            String perfPath = args[4];
            String mode = args[5];
            String[] argsa = {commType,
                             nbHost,
                             nbPort,
                             subTopic, ""};
//
//            String[] argsa = {"niotcp",
//                             "gf5.ucs.indiana.edu",
//                             "3344",
                             //"maverick.tacc.utexas.edu",
                             //"3045",
//                             "/wfs",
//                             ""};

//            String mode = "XML";
//            String perfPath = "C:/projects/XML/perf/filter.txt";
            BinaryFilter b = new BinaryFilter(argsa, mode, perfPath);
            //b.run();
//            b.testFIC();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     *
     * <p>Title: SensorGrid</p>
     *
     * <p>Description: </p>
     *
     * <p>Copyright: Copyright (c) 2006</p>
     *
     * <p>Company: </p>
     *
     * @author Galip Aydin
     * @version 1.0
     */
    class FIConverter extends Thread {

        public FIConverter() {
        }

        public void run() {
            try {
                parse_fi_sax_xml();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        public void parse_fi_sax_xml() throws
                Exception {
        }


    }
}


